#include <iostream>
#include <pthread.h>

// 定义全局变量和自旋锁
int sharedVariable = 0;
pthread_spinlock_t spinlock;

// 线程函数
void *threadFunction(void *arg) {
    int thread_id = *(int*)arg;

    // 加锁
    pthread_spin_lock(&spinlock);

    // 临界区
    std::cout << "Thread " << thread_id << " is incrementing sharedVariable..." << std::endl;
    sharedVariable++;

    // 解锁
    pthread_spin_unlock(&spinlock);

    pthread_exit(NULL);
}

int main() {
    // 初始化自旋锁
    pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);

    // 创建线程
    pthread_t thread1, thread2;
    int id1 = 1, id2 = 2;
    pthread_create(&thread1, NULL, threadFunction, &id1);
    pthread_create(&thread2, NULL, threadFunction, &id2);

    // 等待线程结束
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    // 销毁自旋锁
    pthread_spin_destroy(&spinlock);

    // 输出结果
    std::cout << "sharedVariable = " << sharedVariable << std::endl;

    return 0;
}